package smartgrid;

import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import org.hibernate.criterion.Restrictions;
import org.orm.PersistentException;

@Stateless
public class TariffManager implements TariffInterface {

    /**
     * Get List of tariffs
     * 
     * @return List of tariffs 
     */
    @Override
    public List<Tariff> getTariffs() {
        smartgrid.Tariff[] tariffs = smartgrid.Tariff.listTariffByQuery(null, null);
        return Arrays.asList(tariffs);
    }

    /**
     * Get a list of tariffs by Supplier ID
     * 
     * @param id
     * @return List of tariffs by Supplier ID
     */
    @Override
    public List<Tariff> getTariffsBySupplier(Integer supplierID) {
        smartgrid.Tariff[] tariffs = null;

        try {
            TariffCriteria crit = new TariffCriteria();
            crit.add(Restrictions.eq("Supplier_Tariffs_role.id", supplierID));
            tariffs = smartgrid.Tariff.listTariffByCriteria(crit);

        } catch (PersistentException ex) {
            Logger.getLogger(SuppliersManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        return Arrays.asList(tariffs);
    }

    /**
     * Inserts one tariff
     * 
     * @param supplier Suppliers's ID
     * @param name Tariff's name
     * @return if success: true
     */
    @Override
    public Boolean insertTariff(Integer supplierID, String name) {
        try {
            smartgrid.TariffCriteria crit = new TariffCriteria();
            crit.add(Restrictions.eq("Name", name));
            crit.add(Restrictions.eq("Supplier_Tariffs_role.id", supplierID));
            smartgrid.Tariff tariff = smartgrid.Tariff.loadTariffByCriteria(crit);

            if (tariff == null) {
                smartgrid.TariffProcessor tarProcess = new TariffProcessor();
                tarProcess.setName(name);
                tarProcess.setSupplier_Tariffs_role_supplierID(supplierID);
                tarProcess.setAction("insert");

                if (tarProcess.process().equals("Insert success")) {
                    return true;
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(FacebookAccountManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    /*       PARA TESTES             */
    public static void main(String[] args) {
        Boolean temp;
        TariffManager sm = new TariffManager();
        temp = sm.insertTariff(5, "bifafsdsfdsedass");
        System.out.println("output: " + temp);
    }
}
